package org.springleaf.ui.token;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springleaf.core.exception.TokenException;
import org.springleaf.core.json.JsonData;
import org.springleaf.core.mvc.view.JSONModelAndView;
import org.springleaf.utils.WebHelper;

@Aspect
public class TokenAspect {

	public static Log log = LogFactory.getLog("springleaf");

	/**
	 * 验证token
	 */
	@Around(value = "@annotation(tokenValidate)")
	public Object validateToken(ProceedingJoinPoint jp,
			TokenValidate tokenValidate) throws java.lang.Throwable {

		TokenHelper tokenHelper = new TokenHelper();
		boolean result = tokenHelper.validate(WebHelper.getReq());
		synchronized (WebHelper.getSes()) {//对于每个session此处采用线程同步
			// 如果验证成功
			if (result) {
				// 删除保存的token
				tokenHelper.removeToken(WebHelper.getReq());
				return jp.proceed(jp.getArgs());
			}
		}
		switch (tokenValidate.type()) {
		case FORWARD:
			return new ModelAndView(tokenValidate.value());
		case REDERICT:
			return new ModelAndView(new RedirectView(tokenValidate.value()));
		case JSON:
			return new JSONModelAndView(new JsonData(false, "请勿重复提交"));
		case EXCEPTION:
			throw new TokenException();
		default:
			throw new Exception("缺少指定的ReturnGenerator");
		}

	}
}
